package com.my.note.web.controller;

import com.my.note.pojo.ResourceData;
import com.my.note.pojo.RoleData;
import com.my.note.pojo.RoleResourceData;
import com.my.note.pojo.UserData;
import com.my.note.pojo.UserRoleData;
import com.my.note.security.MD5Util;
import com.my.note.service.UserService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author lilun <a href="mailto:lil@chsi.com.cn">lilun</a>
 * @version $Id$ 2019年03月21 16:39
 */
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {

    @Autowired
    private UserService userService;


    @RequestMapping(value = {"", "index"})
    public String index(Model model) {
        model.addAttribute("userList", userService.getUserVOList());
        return "admin/index";
    }

    @RequestMapping("/user/add")
    public String addUser() {
        return "admin/user/add";
    }

    @RequestMapping("/user/save")
    public String saveUser(@RequestParam String username, @RequestParam String password) {
        UserData userData = userService.getUserByUserName(username);
        if (userData == null) {
            userData = new UserData();
            userData.setId(String.valueOf(LocalDateTime.now().getNano()));
            userData.setUserName(username);
            userData.setPassword(MD5Util.MD5(password));
            userService.save(userData);
            return "admin/index";
        }
        return "admin/user/add";
    }

    @RequestMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable String id) {
        userService.delete(userService.getUserById(id));
        return "redirect:/admin/index";
    }


    @RequestMapping("/userrole/edit/{id}")
    public String editUserRole(@PathVariable String id, Model model) {
        UserData userData = userService.getUserById(id);
        model.addAttribute("userName", userData.getUserName());
        model.addAttribute("userRoleList",
                userService.getRolesByUserId(id).stream().map(p -> p.getId()).collect(Collectors.toList()));
        model.addAttribute("roleList", userService.getRoleList());
        return "admin/userrole/edit";
    }

    @ResponseBody
    @RequestMapping("/userrole/save")
    public Map saveUserRole(@RequestParam String username, @RequestParam(required = false) List<String> role) {
        userService.getUserRoleByUserId(userService.getUserByUserName(username).getId()).stream().forEach(
                userRoleData -> userService.delete(userRoleData));
        if (role == null || role.isEmpty()) {
            return success();
        }
        UserData userData = userService.getUserByUserName(username);
        role.stream().forEach(roleId -> {
            UserRoleData data = new UserRoleData();
            data.setId(String.valueOf(LocalDateTime.now().getNano()));
            data.setRoleId(roleId);
            data.setUserId(userData.getId());
            userService.save(data);
        });
        return success();
    }

    @RequestMapping(value = {"/role/index", "/role"})
    public String roleList(Model model) {
        model.addAttribute("roleList", userService.getRoleVOList());
        return "admin/role/index";
    }

    @RequestMapping("/role/add")
    public String addRole() {
        return "admin/role/add";
    }

    @ResponseBody
    @RequestMapping("/role/save")
    public Map saveRole(@RequestParam String roleName, @RequestParam String mark) {
        RoleData roleData = new RoleData();
        roleData.setId(String.valueOf(LocalDateTime.now().getNano()));
        roleData.setRoleName(roleName);
        roleData.setMark(mark);
        userService.save(roleData);
        return success();
    }

    @RequestMapping("/role/delete/{id}")
    public String deleteRole(@PathVariable String id) {
        userService.delete(userService.getRoleById(id));
        return "redirect:/admin/role";
    }

    @RequestMapping(value = {"/resource/index", "/resource"})
    public String resourceList(Model model) {
        model.addAttribute("resourceList", userService.getResourceList());
        return "admin/resource/index";
    }

    @RequestMapping("/resource/add")
    public String addResource() {
        return "admin/resource/add";
    }

    @ResponseBody
    @RequestMapping("/resource/save")
    public Map saveResource(@RequestParam String url, @RequestParam String mark) {
        ResourceData resourceData = new ResourceData();
        resourceData.setId(String.valueOf(LocalDateTime.now().getNano()));
        resourceData.setUrl(url);
        resourceData.setMark(mark);
        userService.save(resourceData);
        return success();
    }

    @RequestMapping("/resource/delete/{id}")
    public String deleteResource(@PathVariable String id) {
        userService.delete(userService.getResourceById(id));
        return "redirect:/admin/resource";
    }

    @RequestMapping("/roleresource/edit/{id}")
    public String editRoleResource(@PathVariable String id, Model model) {
        RoleData roleData = userService.getRoleById(id);
        model.addAttribute("roleName", roleData.getRoleName());
        model.addAttribute("roleResourceList",
                userService.getResourceListByRoleId(id).stream().map(p -> p.getId()).collect(Collectors.toList()));
        model.addAttribute("resourceList", userService.getResourceList());
        return "admin/roleresource/edit";
    }

    @ResponseBody
    @RequestMapping("/roleresource/save")
    public Map saveRoleResource(@RequestParam String roleName, @RequestParam(required = false) List<String> resource) {
        userService.getRoleResourceByRoleId(userService.getRoleByRoleName(roleName).getId()).stream().forEach(
                roleResourceData -> userService.delete(roleResourceData));
        if (resource == null || resource.isEmpty()) {
            return success();
        }
        RoleData roleData = userService.getRoleByRoleName(roleName);
        resource.stream().forEach(resourceId -> {
            RoleResourceData data = new RoleResourceData();
            data.setId(String.valueOf(LocalDateTime.now().getNano()));
            data.setRoleId(roleData.getId());
            data.setResourceId(resourceId);
            userService.save(data);
        });
        return success();
    }
}
